# coding=utf-8
import random, string, json

from channels.auth import login
from django.contrib.auth import get_user_model, authenticate

from rest_framework import serializers
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from rest_framework_jwt.settings import api_settings

User = get_user_model()
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class UserJWTSerializer(JSONWebTokenSerializer):
    def validate(self, attrs):
        wx_userinfo = json.loads(self.initial_data.get('userInfo'))
        credentials = {
            self.username_field: attrs.get(self.username_field),
            'password': attrs.get('password')
        }
        # all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE，如果是返回 True，否则返回 False。
        if all(credentials.values()):
            user = authenticate(**credentials)
            # {'nickName': 'QiaoFinn_lpf', 'gender': 1, 'language': 'zh_CN', 'city': 'Yantai', 'province': 'Shandong', 'country': 'China', 'avatarUrl': '
            # https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTI39XReVrENhR4tvQOQ5EuN33PoDLUiceRT36Y2icY9TwZBcZ8nSkg8t5CBicbRTyL4Nemk55VjDtDkw/132'}

            userinfo = {
                'gender': wx_userinfo['gender'],
                'head_img': wx_userinfo['avatarUrl'],
                'nickname': wx_userinfo['nickName']
            }

            if not user:
                user = User.objects.create_user(**credentials, **userinfo)
            payload = jwt_payload_handler(user)

            return {
                'token': jwt_encode_handler(payload),
                'user_id': user.id,
                'username': user.username
            }

        else:
            msg = '必须包含“{username field}”和“password.'
            msg = msg.format(username_field=self.username_field)
            raise serializers.ValidationError(msg)


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
